import { View, Image, Text } from "@tarojs/components";
import { useState, useEffect, useMemo } from "react";
import LgButton from "@/pages/components/button";
import Header from "@/pages/messageApp/component/header";
import Taro, { Current } from "@tarojs/taro";
import { requestSystemUrl } from "@/network/baseUrl";
import { HttpGet, HttpPut } from "@/network/servers";
import Utils from "@/utils/index";
import { connect, useDispatch } from "react-redux";
import {
  getBrowserController,
  getNet,
  getStorage,
  getWxSDKParams,
} from "@/pages/components/utils";
import { Popover, Popup } from "antd-mobile";
import { v4 as uuidv4 } from "uuid";
import md5 from "md5";
import { useDocumentTitle, useGetUserInfo } from "@/utils/myUtils";
import proxy from "@/network/proxy";
import "../../images/public/style.css";
import "./index.scss";

const browserController = getBrowserController();
const net = getNet();
const storage = getStorage();
var wx = require("weixin-js-sdk");
const { getNowToken, getQueryVariable } = Utils;

const requireContext = require.context(
  "../../images/fileIcon",
  true,
  /^\.\/.*\.svg$/
);
const svgs = requireContext.keys().map(requireContext);
const keys = requireContext.keys();
let fileObj = {};

keys.map((item, index) => {
  let str = item.replace("./", "").replace(".svg", "");
  fileObj[str] = svgs[index];
});

function App(props) {
  let { noticeAddr, userInfo, baseUrl } = props;

  const dispatch = useDispatch();
  const [detail, setDetail] = useState<any>({});
  const [fileList, setFileList] = useState([]);
  const [imgList, setImgList] = useState([]);
  const [noticeId, setNoticeId] = useState("");
  const [taskId, setTaskId] = useState("");
  const [richTextImg, setRichTextImg] = useState<any>([]);
  const [isRead, setIsRead] = useState(0);

  const [currentFile, setCurrentFile] = useState<any>({});
  const [visible, setVisible] = useState(false);
  const [currentIndex, setCurrentIndex] = useState(null);

  const [webSvrAddr, setWebSvrAddr] = useState('')

  useDocumentTitle("详情", false);

  const getImgsInRichText = (content) => {
    if (!content) {
      return;
    }
    let imgs = content.match(/<img[^>]+>/g);
    if (!imgs) {
      return;
    }
    let arrImg: any = [];
    for (let j = 0; j < imgs.length; j++) {
      imgs[j].replace(
        /<img[^>]*src=['"]([^'"]+)[^>]*>/gi,
        function (match, capture) {
          arrImg.push(capture);
        }
      );
    }
    setRichTextImg(arrImg);
  };

  const getCommonData = () => {
    if (Utils.getQueryVariable("env") === "weapp") {
      // 小程序端的h5
      if (!baseUrl) {
        // 直接跳转当前页面
        requestSystemUrl("000").then((response) => {
          HttpGet({
            //用户信息
            url: response + "/BaseApi/Login/GetOnlineUserInfo",
            data: {
              appid: "210",
              access_token: md5("210").split("").reverse().join(""),
              token: getQueryVariable("lg_tk"),
            },
          }).then((result) => {
            let info = result.Data;
            requestSystemUrl("220").then((res) => {
              let instance = Taro.getCurrentInstance();
              if (instance.router?.params) {
                let params = instance.router.params;
                let id = params.id;
                let taskReleaseId = params.taskReleaseId;
                if (taskReleaseId == "undefined") {
                  taskReleaseId = "";
                }
                setTaskId(taskReleaseId);
                setNoticeId(id);
                let fileUrl = res;
                let url = res + "/api/notice/info/receiver/read/detail";
                let { UserID, UserType, SchoolID } = info;
                dispatch({
                  type: "SET_USERINFO",
                  data: info,
                });
                dispatch({
                  type: "SET_NOTICEADDR",
                  data: res,
                });
                HttpGet({
                  url,
                  data: {
                    userId: UserID,
                    noticeId: id,
                    taskReleaseId: taskReleaseId || "",
                  },
                  load: true,
                }).then((res) => {
                  if (res.code == 200 && res.data) {
                    let attachments = res.data.attachments;
                    if (attachments && attachments.length !== 0) {
                      let imgArr = [] as any,
                        fileArr = [] as any;
                      attachments.map((item) => {
                        // if (typeof item.url === "string" && !item.url.includes(fileUrl) && item.url.includes("/upload/")) {
                        //   item.url =fileUrl +"/upload/" +item.url.split("/upload/")[1];
                        // }
                        let fileType = Utils.getFileType(item.name);
                        if (fileType == "img") {
                          imgArr.push(item);
                        } else {
                          fileArr.push(item);
                        }
                      });

                      setFileList(fileArr);
                      setImgList(imgArr);
                    }
                    setIsRead(res.data.readStatus);
                    setDetail(res.data);
                    let content = res.data.content;
                    getImgsInRichText(content);
                  } else {
                    Taro.showToast({
                      title: res.msg,
                      icon: "none",
                    });
                  }
                });
              }
            });
          });
        });
      } else {
        //应用内跳转
        let instance = Taro.getCurrentInstance();
        if (instance.router?.params) {
          let params = instance.router.params;
          let id = params.id;
          let taskReleaseId = params.taskReleaseId;
          if (taskReleaseId == "undefined") {
            taskReleaseId = "";
          }
          setTaskId(taskReleaseId);
          setNoticeId(id);
          let url = noticeAddr + "/api/notice/info/receiver/read/detail";
          let { UserID, UserType, SchoolID } = userInfo;
          HttpGet({
            url,
            data: {
              userId: UserID,
              noticeId: id,
              taskReleaseId: taskReleaseId || "",
            },
            load: true,
          }).then((res) => {
            if (res.code == 200 && res.data) {
              let attachments = res.data.attachments;
              if (attachments && attachments.length !== 0) {
                let imgArr = [],
                  fileArr = [];
                attachments.map((item) => {
                  // if (typeof item.url === "string" && !item.url.includes(noticeAddr) && item.url.includes("/upload/")) {
                  //   item.url =noticeAddr + "/upload/" + item.url.split("/upload/")[1];
                  // }
                  let fileType = Utils.getFileType(item.name);
                  if (fileType == "img") {
                    imgArr.push(item);
                  } else {
                    fileArr.push(item);
                  }
                });

                setFileList(fileArr);
                setImgList(imgArr);
              }
              setIsRead(res.data.readStatus);
              setDetail(res.data);
              let content = res.data.content;
              getImgsInRichText(content);
            } else {
              Taro.showToast({
                title: res.msg,
                icon: "none",
              });
            }
          });
        }
      }
    } else {
      // app内 1.应用内跳转(不需要获取通知地址和用户信息) 2.直接跳转
      let instance = Taro.getCurrentInstance();

      const browserController = getBrowserController();
      let height = browserController.getStatusBarHeight();
      if (instance.router?.params) {
        let params = instance.router.params;
        let id = params.id;
        let taskReleaseId = params.taskReleaseId;
        if (taskReleaseId == "undefined") {
          taskReleaseId = "";
        }
        // console.log(params);

        setIsRead(isRead);
        setNoticeId(id);
        setTaskId(taskReleaseId);
        Taro.getSysWeb({ sysId: "000" }, "web", async function (baseAddr) {
          let userInfo = await useGetUserInfo(
            baseAddr,
            "000",
            Utils.getNowToken()
          );
          const { UserID: userId } = userInfo;
          dispatch({ type: "SET_USERINFO", data: userInfo });
          HttpGet({
            url: "api/commons/system/getServerInfo",
            data: {
              sysIds: "264",
            },
          }).then((response) => {
            dispatch({
              type: "SET_NOTICEADDR",
              data: response.data[0]?.webSvrAddr,
            });
            setWebSvrAddr(response.data[0]?.webSvrAddr)
            let url =
              response.data[0]?.webSvrAddr +
              "/api/notice/info/release/detail";
            HttpGet({
              url,
              data: {
                userId,
                noticeId: id,
                taskReleaseId: taskReleaseId || "",
                eduId: userInfo.SchoolID
              },
              load: true,
            }).then((res) => {
              if (res.code == 200 && res.data) {
                let attachments = res.data.attachments;
                if (attachments && attachments.length !== 0) {
                  let imgArr = [],
                    fileArr = [];
                  attachments.map((item) => {
                    let fileType = Utils.getFileType(item.name);
                    if (fileType == "img") {
                      imgArr.push(item);
                    } else {
                      fileArr.push(item);
                    }
                  });

                  setFileList(fileArr);
                  setImgList(imgArr);
                }
                setIsRead(res.data.readStatus);
                setDetail(res.data);
                let content = res.data.content;
                getImgsInRichText(content);
              } else {
                Taro.showToast({
                  title: res.msg,
                  icon: "none",
                  duration: 2000,
                });
              }
            });
          });
        });
      }
    }
  };

  //查收
  const hasCheck = (
    sign,
    id = noticeId,
    tId = taskId,
    noticeUrl = noticeAddr,
    user = userInfo
  ) => {
    if (detail.sign && detail.sign === "1" && !sign) {
      //需要手签
      Taro.showModal({
        title: "提示",
        content: "当前通知查收需手签确认，是否前往手签？",
        confirmColor: "#0099ff",
        success: function (res) {
          if (res.confirm) {
            Taro.navigateTo({ url: "/pages/messageApp/sign/index" });
          } else if (res.cancel) {
            console.log("用户点击取消");
          }
        },
      });
      return;
    }
    // debugger
    let url;
    url = noticeUrl + `/api/notice/receiver/reply`;
    HttpPut({
      url,
      data: {
        userId: user.UserID,
        noticeId: id,
        taskReleaseId: tId || "",
        signContent: sign || "",
      },
    }).then((response) => {
      if (response.code == 200) {
        getCommonData();
        setTimeout(() => {
          Taro.showToast({
            title: "查收成功",
          });
        }, 500);
      } else {
        Taro.showToast({
          title: response.msg,
          icon: "none",
        });
      }
    });
  };

  const getFileName = (fileName: string) => {
    if (!fileName) {
      return "文件";
    }

    let pot1 = fileName.lastIndexOf(".");
    return fileName.substring(0, pot1);
  };

  const download = async (item, index?) => {
    console.log(item)
    console.log(webSvrAddr)
    setVisible(false);
    if (item?.preView || storage.get(String(item?.attachmentId))) {
      //当前文件已下载，直接预览
      console.log('已下载')
      showFile(item);
      return;
    }

    let fileName = getFileName(item.name);
    let url = webSvrAddr + item.url;
    if (Utils.getSystemInfo() === "weapp") {
      console.log("weapp")
      const params = await getWxSDKParams([]);
      wx.config(params);
      try {
        console.log("预览地址:" + url);
        browserController.openFileForWebview(wx, { fileUrl: url, fileName });
      } catch (error) {
        Taro.showToast({ title: error, icon: "none" });
      }
    } else {
      let arr = fileList.concat([]);
      net.downloadFile({
        url,
        fileName: item.name,
        onProgress: (process) => {
          Taro.showToast({
            icon: "loading",
            title: `正在下载${process}%`,
          });
        },
        onSuccess: (path) => {
          // Taro.showToast({
          //   title: '下载成功',
          //   icon: 'success',
          //   duration: 2000

          // })
          arr[index].preView = true;
          storage.set(item.attachmentId, path);
          browserController.openFileReader(path); //下载完就预览
          setFileList(arr);
        },
        onError: (error) => {
          Taro.showToast({
            title: "下载失败",
            icon: "none",
            duration: 2000,
          });
        },
      });
    }
  };

  const showImg = (e) => {
    e & e.stopPropagation();
    if (e?.target?.nodeName !== "IMG") {
      return;
    }
    let img = e.target?.src,
      previewUrl = "";
    if (!img) {
      return;
    }

    Taro.previewImage({
      current: img,
      urls: richTextImg,
    });
  };

  const showPreView = (item) => {
    let arr = [];
    imgList.map((t) => {
      arr.push(t.url);
    });
    Taro.previewImage({
      current: item.url, // 当前显示图片的http链接
      urls: arr, // 需要预览的图片http链接列表
    });
  };

  const showFile = (item, e?) => {
    e && e.stopPropagation();
    browserController.openFileReader(storage.get(item.attachmentId));
  };

  const initWxSdk = async () => {
    const params = getWxSDKParams(["previewImage", "getLocation"]);
    wx.config(params);
    wx.ready(function () {
      // config信息验证后会执行 ready 方法，所有接口调用都必须在 config 接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在 ready 函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在 ready 函数中。
      console.log("ready");
    });
    wx.error(function (res) {
      // config信息验证失败会执行 error 函数，如签名过期导致验证失败，具体错误信息可以打开 config 的debug模式查看，也可以在返回的 res 参数中查看，对于 SPA 可以在这里更新签名。
      console.log(res);
    });
  };

  const resetFileList = (e?: TouchEvent) => {
    e && e.stopPropagation();
    let arr = fileList.concat([]);
    Array.isArray(arr) &&
      arr.length > 0 &&
      arr.forEach((item: any) => {
        item.visible = false;
      });
    setFileList(arr);
  };

  const handleSaveInDisk = (e, item) => {
    e && e.stopPropagation();
    setVisible(false);
    resetFileList();
    Taro.showLoading({
      title: "文件上传中",
    });
    console.log(item);
    if (Number(item.size) > 4194304) {
      Taro.showToast({
        title: "文件大小不能大于4M",
        icon: "none",
      });
      return;
    }
    Taro.downloadFile({
      url: item.url,
      success: (result) => {
        Taro.getSysWeb(
          { sysId: "261", schoolId: userInfo.SchoolID },
          "web",
          function (data) {
            let uploadUrl =
              data
                .replace("/Web_PersonalDisk/", "/http_PersonalDisk/")
                .replace("/web_personaldisk/", "/http_PersonalDisk/") +
              "/WebUploadHandler.ashx";
            console.log(item);
            if (Utils.getSystemInfo() === "weapp") {
              uploadUrl = proxy.transmitUrlToVisit(uploadUrl);
            }
            let uploadTask = Taro.uploadFile({
              url: uploadUrl, //仅为示例，非真实的接口地址
              filePath: result.tempFilePath,
              name: item.name,
              formData: {
                method: "doUpload",
                userId: userInfo.UserID,
                name: item.name,
                Guid: uuidv4(),
                chunk: 0,
                chunks: 0,
                chunkSize: 2,
                isPaused: 0,
              },
              success(res) {
                let res1 = JSON.parse(res.data);
                HttpGet({
                  url: data + "SysMgr/PersonDisk/api/Service_PersonDisk.ashx",
                  data: {
                    token: Utils.getNowToken(),
                    method: "InsertFileInfo",
                    params: `${item.name}||1|${res1.filePath}|${item.size}`,
                    userId: userInfo.UserID,
                  },
                }).then(() => {
                  Taro.hideLoading();
                  Taro.showToast({
                    title: "保存成功，请前往个人网盘查看",
                  });
                });
              },
            });
            uploadTask.progress((res) => {
              Taro.showToast({
                icon: "loading",
                title: `保存进度${res.progress}%`,
                duration: 10000,
                mask: true,
              });
            });
          }
        );
      },
    });
  };

  useEffect(() => {
    if (Utils.getSystemInfo() === "weapp") {
      initWxSdk();
    }
    getCommonData();

    // 挂载处理签名的事件回调
    Taro.eventCenter.on("confirmWithSign", hasCheck);

    return () => {
      window.getNoticeList &&
        typeof window.getNoticeList === "function" &&
        window.getNoticeList();
      window.getNewRemindCount &&
        typeof window.getNewRemindCount === "function" &&
        window.getNewRemindCount();

      // 取消监听
      Taro.eventCenter.off("confirmWithSign", hasCheck);
    };
  }, []);

  return (
    <View className="noticeDetail" onClick={(e) => resetFileList(e)}>
      <Header title="通知详情" isBlod={false} isLeft={true} />
      <View className="notice_detail_main">
        {detail ? (
          <View className="header">
            <View className="title">{detail.title}</View>
            <View className="noticeInfo">
              <Text>{detail?.taskReleaseTime || detail.releaseTime}</Text>
              <Text style={{ margin: "0 10px", color: "#999999" }}>|</Text>
              <Text>{detail.userName}</Text>
              {typeof detail.readCount == "number" ? <Text>|</Text> : null}
              {typeof detail.readCount == "number" ? (
                <Text>{detail.readCount || 0}(已阅)</Text>
              ) : null}
            </View>
          </View>
        ) : null}

        {detail ? (
          <View
            className="content"
            id="content"
            onClick={showImg}
            dangerouslySetInnerHTML={{ __html: detail.content }}
          ></View>
        ) : (
          ""
        )}
        {
          <View className="attachment">
            <View className="imgBox">
              {imgList.map((item) => {
                return (
                  <View className="imgItem" onClick={() => showPreView(item)}>
                    <Image
                      className="imgSrc"
                      src={webSvrAddr+item.url}
                      mode="aspectFill"
                    />
                  </View>
                );
              })}
            </View>
            <View className="fileBox">
              {fileList.map((item: any, index) => {
                let icon = Utils.getFileType(decodeURIComponent(item.name));
                let fileIcon = {
                  img: "0a00901",
                  doc: "0a00101",
                  ppt: "0a00201",
                  pdf: "0a00501",
                  txt: "0a00401",
                  xls: "0a00301",
                  music: "0a00601",
                  video: "0a00701",
                  html: "0a01001",
                  zip: "0a01201",
                  otr: "0a01101",
                };
                let src = fileObj[fileIcon[icon]];
                // console.log(`fileObj`, fileObj['0a00101'])
                // console.log(`src`, fileIcon[icon])
                let size = Utils.getFileSize(item.size);
                return (
                  <Popover
                    content={
                      <View onClick={(e) => handleSaveInDisk(e, item)}>
                        保存到我的个人网盘
                      </View>
                    }
                    mode="dark"
                    placement="top"
                    visible={item.visible}
                  >
                    <View
                      className="docItem"
                      onClick={(e) => {
                        e && e.stopPropagation();
                        setVisible(true);
                        setCurrentFile(item);
                        setCurrentIndex(index);
                      }}
                    >
                      <View className="docIcon">
                        <Image className="docImg" src={src} />
                      </View>
                      <View className="docInfo">
                        <View className="docName oneline">
                          {decodeURIComponent(item.name)}
                        </View>
                        <View className="docSize">{size}</View>
                      </View>
                      <View className="downLoadIcon_content"></View>
                    </View>
                  </Popover>
                );
              })}
            </View>
          </View>
        }
      </View>
      {detail ? (
        detail.replyType == 2 && detail.replyStatus == 0 ? (
          <View className="hasReadBox">
            <LgButton onClick={hasCheck} type="B" width="640">
              {" "}
              查收{" "}
            </LgButton>
          </View>
        ) : null
      ) : (
        ""
      )}
      <Popup
        visible={visible}
        onMaskClick={() => {
          setVisible(false);
        }}
        bodyStyle={{
          borderTopLeftRadius: "8px",
          borderTopRightRadius: "8px",
          // minHeight: '256px'
        }}
      >
        <View className="file_pop">
          <View className="file_name">{currentFile?.name || "--"}</View>
          <View
            className="option_row"
            onClick={() => download(currentFile, currentIndex)}
          >
            预览
          </View>
          {userInfo?.SchoolID === "S-8800152" ? (
            <View
              className="option_row"
              onClick={(e) => handleSaveInDisk(e, currentFile)}
            >
              保存到我的网盘
            </View>
          ) : (
            ""
          )}
          <View className="line"></View>
          <View className="cancle" onClick={() => setVisible(false)}>
            取消
          </View>
        </View>
      </Popup>
    </View>
  );
}

const mainProps = ({ commonData }) => {
  return {
    userInfo: commonData.userInfo,
    env: commonData.env,
    noticeAddr: commonData.noticeAddr,
    baseUrl: commonData.baseUrl,
  };
};

export default connect(mainProps)(App);
